<?php

namespace app\api\controller\app;

use addons\epay\library\Service;
use app\admin\model\Chargecode;
use app\admin\model\Notice;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\shop\Commission;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopfav;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoproomset;
use app\admin\model\Shoptuan;
use app\admin\model\Shopwifi;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Userweixin;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Shop extends Api
{
    protected $noNeedLogin = ['chargeNotify', 'sxfCallback', 'shopList', 'getChargeInfo', 'roomInfo', 'getNotice', 'roomTime', 'getRoomList','getShopMinMoney'];
    protected $noNeedRight = '*';

    protected $app = null;

    public function _initialize()
    {
        parent::_initialize();

    }

    public function shopList()
    {

        $keyword = $this->request->param('keyword');
        $orgId = $this->request->param('orgId');
        $where = array();
        $where['org_id'] = $orgId;
        if ($keyword != '') {
            $where['name'] = array('like', "'%" . $keyword . "%'");
        }
        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->where($where)->select();
        $this->success('', $list);
    }

    public function shopList2()
    {

        $keyword = $this->request->param('keyword');
        $lat = $this->request->param('lat');
        $lng = $this->request->param('lng');

        if (!$lat) {
            $lat = 28.2068360;
            $lng = 112.8823270;
        }

        $orgId = $this->request->param('orgId');

        $where = "";
        if ($keyword != '') {
            $where = "where name like '%" . $keyword . "%'";
        }

        $sql = "select * from(
SELECT id,name,address,logo,lng,lat,is_join_balance,org_id,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-lat*PI()/180)/2),2)+COS($lat*PI()/180)*COS(lat*PI()/180)*POW(SIN(($lng*PI()/180-lng*PI()/180)/2),2)))*1000) AS distance
FROM q_shop  $where )  as tmp_table_name
order by distance";

        error_log("==sql==" . $sql);
        $shopModel = new \app\admin\model\Shop();
        $list = $shopModel->query($sql);
        $this->success('', $list);
    }

    /**
     * 获取店铺充值套餐和用户店铺与额
     */
    public function getChargeInfo()
    {

        $user = $this->auth->getUser();
        $shop_id = $this->request->param('shop_id');

        $shopChargeConfigModel = new Shopchargeconfig();
        $chargeList = $shopChargeConfigModel->where('shop_id', $shop_id)->order('amount', 'asc')->select();

        $ret = array();
        $userBalanceModel = new Userbalance();
        $totalAmount = $userBalanceModel->balance($shop_id, $user['id']);


        $userAllBalanceModel = new Userallbalance();
        $allBalance = $userAllBalanceModel->userBalance($user['id']);

        $ret['balance'] = formatMoney($totalAmount + $allBalance);
        $ret['chargeList'] = $chargeList;
        $ret['shopBalance'] = formatMoney($totalAmount);//店铺余额
        $ret['allBalance'] = $allBalance;//平台余额

        $this->success('', $ret);

    }


    public function doCharge()
    {

        $user = $this->auth->getUser();
        $charge_id = $this->request->param('charge_id');
        $orgId = $this->request->param('orgId');
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $charge_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $charge['shop_id'])->find();
        if ($orgId == '') {
            $orgId = $shop['org_id'];
        }
        $order_no = getOrderSn();
        $shopChargeModel = new Shopcharge();
        $dbCharge = array();
        $dbCharge['user_id'] = $user['id'];
        $dbCharge['order_no'] = $order_no;
        $dbCharge['create_time'] = time();
        $dbCharge['charge_id'] = $charge_id;
        $dbCharge['shop_id'] = $charge['shop_id'];
        $dbCharge['amount'] = $charge['amount'];
        $dbCharge['get_amount'] = $charge['get_amount'];
        $dbCharge['org_id'] = $orgId;


        $dbCharge['pay_rate'] = formatMoney($shop['pay_rate'] * $dbCharge['amount'] / 100);
        $dbCharge['rate'] = formatMoney($shop['ratio'] * $dbCharge['amount'] / 100);


        $id = $shopChargeModel->insertGetId($dbCharge);
        if ($id > 0) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

//            $params = [
//                'out_trade_no' => $order_no,//你的订单号
//                'total_fee' => $charge['amount'] * 100,//单位元
//                'body' => $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'],
//                'openid' => $wx['openid'],
//
//            ];
//
//            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/chargeNotify";
//            $config = Service::getConfig("wechat");
//            $config['notify_url'] = $url;
//            $pay = Pay::wechat($config);
//            $result = $pay->miniapp($params);

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/sxfCallback";

            $orgModel = new Org();
            $org = $orgModel->where('id', $orgId)->find();
            $req['mno'] = $org['mno'];
            $req['ordNo'] = $order_no;
            $req['amt'] = $charge['amount'];

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";

            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];
            $body = $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'];
            $req['subject'] = "店铺会员充值";
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;

            error_log("===req===" . json_encode($req));


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];
                $this->success('下单成功', $info);

            } else {
                $this->error($bizMsg);
            }


        } else {
            $this->error("充值失败，请联系客服");
        }


    }


    public function doChargeFz()
    {

        $user = $this->auth->getUser();
        $charge_id = $this->request->param('charge_id');
        $orgId = $this->request->param('orgId');
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $charge_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $charge['shop_id'])->find();
        if ($orgId == "") {
            $orgId = $shop['org_id'];
        }
        $order_no = getOrderSn();
        $shopChargeModel = new Shopcharge();
        $dbCharge = array();
        $dbCharge['user_id'] = $user['id'];
        $dbCharge['order_no'] = $order_no;
        $dbCharge['create_time'] = time();
        $dbCharge['charge_id'] = $charge_id;
        $dbCharge['shop_id'] = $charge['shop_id'];
        $dbCharge['amount'] = $charge['amount'];
        $dbCharge['get_amount'] = $charge['get_amount'];
        $dbCharge['org_id'] = $orgId;


        $dbCharge['pay_rate'] = formatMoney($shop['pay_rate'] * $dbCharge['amount'] / 100);
        $dbCharge['rate'] = formatMoney($shop['ratio'] * $dbCharge['amount'] / 100);


        $id = $shopChargeModel->insertGetId($dbCharge);
        if ($id > 0) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

//            $params = [
//                'out_trade_no' => $order_no,//你的订单号
//                'total_fee' => $charge['amount'] * 100,//单位元
//                'body' => $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'],
//                'openid' => $wx['openid'],
//
//            ];
//
//            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/chargeNotify";
//            $config = Service::getConfig("wechat");
//            $config['notify_url'] = $url;
//            $pay = Pay::wechat($config);
//            $result = $pay->miniapp($params);

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/sxfCallback";


            $orgModel = new Org();
            $org = $orgModel->where('id', $orgId)->find();


            error_log($shop['id'] . "==org==" . json_encode($org));
            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
            $mno = $org['mno'];
            if ($shopMno) {
                if ($shopMno['ratio'] == 100) {
                    //走挂靠
                    $mno = $shopMno['mno'];
                } else {
                    //走分账
                    $pay_price = $charge['amount'];
                    $listMnos = $shopMnoModel->where('shop_id', $shop['id'])->select();
                    $fs = array();
                    $realPay = formatMoney($pay_price - $pay_price * 0.006);
                    foreach ($listMnos as $key => $val) {
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $val['mno'];
                        $fusruleId['allotValue'] = formatMoney($val['ratio'] * $realPay / 100);
                        $fs[] = $fusruleId;
                    }
                    $req['fusruleId'] = $fs;
                }
            }


            $req['mno'] = $mno;
            $req['ordNo'] = $order_no;
            $req['amt'] = $charge['amount'];

            error_log("===req==" . json_encode($req));

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];
            $body = $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'];
            $req['subject'] = $body;
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);

            error_log("====res===" . json_encode($res));
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];
                $this->success('下单成功', $info);

            } else {
                $this->error($bizMsg);
            }


        } else {
            $this->error("充值失败，请联系客服");
        }


    }


    public function doChargeFzMore()
    {

        $user = $this->auth->getUser();
        $charge_id = $this->request->param('charge_id');
        $orgId = $this->request->param('orgId');
        $shopchargeconfigModel = new Shopchargeconfig();
        $charge = $shopchargeconfigModel->where('id', $charge_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $charge['shop_id'])->find();
        if ($orgId == "") {
            $orgId = $shop['org_id'];
        }
        $order_no = getOrderSn();
        $shopChargeModel = new Shopcharge();
        $dbCharge = array();
        $dbCharge['user_id'] = $user['id'];
        $dbCharge['order_no'] = $order_no;
        $dbCharge['create_time'] = time();
        $dbCharge['charge_id'] = $charge_id;
        $dbCharge['shop_id'] = $charge['shop_id'];
        $dbCharge['amount'] = $charge['amount'];
        $dbCharge['get_amount'] = $charge['get_amount'];
        $dbCharge['org_id'] = $orgId;


        $dbCharge['pay_rate'] = formatMoney($shop['pay_rate'] * $dbCharge['amount'] / 100);
        $dbCharge['rate'] = formatMoney($shop['ratio'] * $dbCharge['amount'] / 100);


        $id = $shopChargeModel->insertGetId($dbCharge);
        if ($id > 0) {

            $userwxModel = new Userweixin();
            $wx = $userwxModel->where('user_id', $user['id'])->find();

//            $params = [
//                'out_trade_no' => $order_no,//你的订单号
//                'total_fee' => $charge['amount'] * 100,//单位元
//                'body' => $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'],
//                'openid' => $wx['openid'],
//
//            ];
//
//            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/chargeNotify";
//            $config = Service::getConfig("wechat");
//            $config['notify_url'] = $url;
//            $pay = Pay::wechat($config);
//            $result = $pay->miniapp($params);

            $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/shop/sxfCallback";


            $orgModel = new Org();
            $org = $orgModel->where('id', $orgId)->find();


            error_log($shop['id'] . "==org==" . json_encode($org));
            $shopMnoModel = new Shopmno();
            $shopMno = $shopMnoModel->where('shop_id', $shop['id'])->find();
            $mno = $org['mno'];
            if ($shopMno) {
                if ($shopMno['ratio'] == 100) {
                    //走挂靠
                    $mno = $shopMno['mno'];
                } else {
                    //走分账
                    $pay_price = $charge['amount'];

                    $listMnos = $shopMnoModel->where('shop_id', $shop['id'])->select();
                    $fs = array();
                    $realPay = formatMoney($pay_price - $pay_price * 0.006);
                    foreach ($listMnos as $key => $val) {
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $val['mno'];
                        $fusruleId['allotValue'] = formatMoney($val['ratio'] * $realPay / 100);
                        $fs[] = $fusruleId;

                    }

                    $req['fusruleId'] = $fs;
                }
            }


            $req['mno'] = $mno;
            $req['ordNo'] = $order_no;
            $req['amt'] = $charge['amount'];

            $req['payType'] = "WECHAT";
            $req['payWay'] = "03";
            $req['subAppid'] = $org['app_id'];
            $req['userId'] = $wx['openid'];
            $body = $shop['name'] . "充值" . $charge['amount'] . "得" . $charge['get_amount'];
            $req['subject'] = $body;
            $req['tradeSource'] = "01";
            $req['trmIp'] = get_client_ip();
            $req['notifyUrl'] = $url;


            $vbillService = new VbillService();
            $res = $vbillService->jsApi($req);
            $result = json_decode($res, true);
            $bizCode = $result['respData']['bizCode'];
            $bizMsg = $result['respData']['bizMsg'];

            if ($bizCode == '0000') {
                $info['order_no'] = $order_no;
                $info['payInfo'] = $result['respData'];
                $this->success('下单成功', $info);

            } else {
                $this->error($bizMsg);
            }


        } else {
            $this->error("充值失败，请联系客服");
        }


    }

    public function sxfCallback()
    {

        $param = file_get_contents("php://input");
        error_log("===order===callback=====" . json_encode($param));

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $shopChargeModel = new Shopcharge();
            $order = $shopChargeModel->where('order_no', $out_trade_no)->find();
            $shopChargeModel->where('id', $order['id'])->update(['status' => 'payed']);
            $userBalanceModel = new Userbalance();
            $shopchargeconfigModel = new Shopchargeconfig();
            $charge = $shopchargeconfigModel->where('id', $order['charge_id'])->find();
            $balance = $userBalanceModel->where('b_type', 'charge')->where('order_id', $order['id'])->find();
            if (!$balance) {
                $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'in', 'amount' => $charge['get_amount'], 'create_time' => time(),
                    'shop_id' => $charge['shop_id'], 'order_id' => $order['id'], "mark" => "用户充" . $charge['amount'] . "得" . $charge['get_amount']]);

                $shopModel = new \app\admin\model\Shop();
                $shopOrderProfitModel = new Shoporderprofit();
                $shop = $shopModel->where('id', $charge['shop_id'])->find();

                $pay_price = $order['amount'];
                if ($shop['profit_type'] == 1) {//根据抽佣类型类来抽点
                    //扣除支付通道费
                    $shopProfit = $pay_price - formatMoney($pay_price * $shop['pay_rate'] / 100);;
                    $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                        'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney($shopProfit)]);

                } else {
                    //商家分润，包含扣除支付通道费
                    $shopProfit = $pay_price - formatMoney($pay_price * $shop['ratio'] / 100) - formatMoney($pay_price * $shop['pay_rate'] / 100);
                    $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                        'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney($shopProfit)]);
                    //代理商分润
                    if ($shop['agent_ratio'] > 0) {
                        $userOrderProfitModel = new Userorderprofit();
                        $agentFee = $shop['agent_ratio'] * $order['amount'] / 100;
                        if ($agentFee > 0) {
                            $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                                'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                        }
                    }
                }

//                /**
//                 * 商家分润
//                 */
//                $pay_price = $order['amount'];
//                $pay_rate = formatMoney($pay_price * 0.006);
//                $shopProfit = $pay_price - formatMoney($shop['ratio'] * $pay_price / 100) - $pay_rate;
//                $shopOrderProfitModel = new Shoporderprofit();
//                $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
//                    'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => $shopProfit]);
//                /**
//                 * 代理商分润
//                 */
//                if ($shop['agent_ratio'] > 0) {
//
//                    $userOrderProfitModel = new Userorderprofit();
//                    $agentFee = $shop['agent_ratio'] * $order['amount'] / 100;
//                    if ($agentFee > 0) {
//                        $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
//                            'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
//                    }
//                }
            }

        }
    }

    public function chargeNotify()
    {

        $config = Service::getConfig('wechat');
        $pay = Pay::wechat($config);
        $result = $pay->verify();

        $out_trade_no = $result['out_trade_no'];
        $amount = $result['total_fee'] / 100;


        if (in_array($result['return_code'], ['SUCCESS'])) {

            $shopChargeModel = new Shopcharge();
            $order = $shopChargeModel->where('order_no', $out_trade_no)->find();
            $shopChargeModel->where('id', $order['id'])->update(['status' => 'payed']);
            $userBalanceModel = new Userbalance();
            $shopchargeconfigModel = new Shopchargeconfig();
            $charge = $shopchargeconfigModel->where('id', $order['charge_id'])->find();
            $userBalanceModel->insert(['user_id' => $order['user_id'], 'type' => 'in', 'amount' => $charge['get_amount'], 'create_time' => time(),
                'shop_id' => $charge['shop_id'], 'order_id' => $order['id'], "mark" => "用户充" . $charge['amount'] . "得" . $charge['get_amount']]);

            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $charge['shop_id'])->find();


            /**
             * 商家分润
             */
            $shopOrderProfitModel = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['amount'] - $order['rate'] - $order['pay_rate']))]);


            /**
             * 代理商分润
             */
            if ($shop['agent_ratio'] > 0) {

                $userOrderProfitModel = new Userorderprofit();
                $agentFee = $shop['agent_ratio'] * $order['amount'] / 100;
                if ($agentFee > 0) {
                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $charge['shop_id'], 'type' => 'charge',
                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                }


            }

        }
        return $pay->success();

    }

    public function getDetail()
    {

        $id = $this->request->param('id');
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $id)->find();
        $shop['logo'] = cdnurl($shop['logo'], true);

        if ($shop['video'] != "") {
            $shop['video'] = cdnurl($shop['video'], true);
        }
        $cover = array();
        if ($shop['cover'] != "") {
            $covers = explode(",", $shop['cover']);

            foreach ($covers as $key => $val) {
                $cover[] = cdnurl($val, true);
            }
        } else {
            if ($shop['org_id'] == 53) {
                $cover[] = cdnurl("/uploads/20231208/173ff1ecdaf96578fca981fe1bc9004f.jpg", true);
            }
        }
        $tag = array();
        if ($shop['tag'] != "") {
            $tag = explode(",", $shop['tag']);
        }
        if ($shop['wx_code'] != "") {
            $shop['wx_code'] = cdnurl($shop['wx_code'], true);
        }

        $shop['cover'] = $cover;
        $shop['tag'] = $tag;

        $shopFavModel = new Shopfav();

        $isFav = -1;
        $fav = $shopFavModel->where('shop_id', $shop['id'])->find();
        if ($fav) {
            $isFav = 1;
        }
        $shop['isFav'] = $isFav;

        $shopTuanModel = new Shoptuan();
        $tuanList = $shopTuanModel->where('shop_id', $shop['id'])->where('status', 1)->select();
        $shop['tuanList'] = $tuanList;
        $this->success('', $shop);

    }

    public function getRoomList()
    {

        $shop_id = $this->request->param('shop_id');
        $shopRoomModel = new Shoproom();

        //根据包厢状态排序，自动将空闲包厢置顶
        $list = $shopRoomModel->with(['set'])->where('shop_id', $shop_id)->order(['status' => 'asc', 'weigh' => 'desc'])->select();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $shop_id)->find();
        $isClean = $shop['is_clean_book'];
        $shopBookTime = new Shoproombook();
        $roomCleanModel = new Roomclean();

        $cleanList = $roomCleanModel->where('shop_id', $shop_id)->where('start_time', "<", time())->where('end_time', ">", time())->where('status', 'in', ['undo', 'doing'])->select();

        foreach ($list as $key => $val) {


            $setList = $val['set'];

            $setArrayList = array();
            if (count($setList) > 3) {
                foreach ($setList as $k => $v) {
                    if ($k < 2) {
                        $setArrayList[] = $v;
                    }
                    if ($v['time'] != "") {
                        $setArrayList[] = $v;
                    }
                }

                $list[$key]['set2'] = $setArrayList;
            } else {
                $list[$key]['set2'] = $setList;
            }

            $list[$key]['logo'] = cdnurl($val['logo'], true);

            $covers = explode(",", $val['cover']);
            $cover = array();
            foreach ($covers as $k => $v) {
                if ($v != "") {
                    $cover[] = cdnurl($v, true);
                }
            }
            $list[$key]['cover'] = $cover;
            $tag = explode(",", $val['tag']);
            $tags = array();
            foreach ($tag as $k => $v) {
                if ($v != "") {
                    if ($k < 7) {
                        $tags[] = $v;
                    }
                }
            }
            $list[$key]['tag'] = $tags;
            $time = getHourSlot();
            $list[$key]['useEndTime'] = -1;

            $endTime = "";
            $bookList = $shopBookTime->where('status', 'in', ['undo', 'doing'])->where('room_id', $val['id'])->where('end_time', ">=", time())->select();


            if ($val['is_clean'] == -1) {
                $list[$key]['isClean'] = 1;
            } else {
                $list[$key]['isClean'] = -1;

            }

            foreach ($cleanList as $k2 => $v2) {

                if ($v2['room_id'] == $val['id']) {

                    if ($v2['status'] == 'doing') {
                        $list[$key]['isClean'] = 2;
                    }
                }
            }

            $isFree = true;
            $endTime = "";
            $endDate = "";
            foreach ($time as $k => $v) {
                $startDate = $v['time'] . ":00";
                $startDate2 = $v['time'] . ":30";

                $startTime = strtotime($startDate);
                $startTime2 = strtotime($startDate2);

                $time[$k]['isBook'] = false;


                foreach ($bookList as $k1 => $v1) {
                    if ($startTime >= $v1['start_time'] && $startTime <= $v1['end_time']) {
                        $time[$k]['isBook'] = true;
                        $isFree = false;

                    }
                    if ($startTime2 >= $v1['start_time'] && $startTime2 <= $v1['end_time']) {
                        $time[$k]['isBook'] = true;
                        $isFree = false;
                    }


                    if ($v1['status'] != 'done') {
                        if (time() >= $v1['start_time'] && time() <= $v1['end_time']) {
                            $list[$key]['useEndTime'] = "使用中" . date("H:i", $v1['end_time']) . "结束";
                        }
                    }

                    $endTime = date("H:i", strtotime("+20 minute", $v1['end_time']));
                    $endDate = date("Y-m-d", $v1['end_time']);
                }

            }

            $list[$key]['endTime'] = $endTime;
            $list[$key]['endDate'] = $endDate;
            $list[$key]['time'] = $time;
            $list[$key]['isFree'] = $isFree;
            $list[$key]['isCleanBook'] = $isClean;


        }

        $this->success('', $list);
    }


    //最近5天的时间
    public function roomTime()
    {

        $time = getFiveDate();
        $this->success('', $time);
    }


    /**
     * 时间区间获取
     */
    public function roomTimeOne()
    {

        $room_id = $this->request->param('id');
        $date = $this->request->param('date');

        $next = getNextTime();
        if ($date == date("Y-m-d")) {
            $timeList = getTimeList();

        } else {
            $timeList = getTimeList2();
        }


        foreach ($next as $key => $val) {
            $timeList[] = $val;
        }


        $startTime = strtotime($date . " 00:00:00");
        $endTime = strtotime($date . " 23:59:59");

        $shopBookTime = new Shoproombook();
        $bookList = $shopBookTime->where('room_id', $room_id)->where('status', "<>", 'done')->select();


        $cleanRoomModel = new Roomclean();
        $cleanList = $cleanRoomModel->where('room_id', $room_id)->where('status', "<>", 'done')->select();
        $nextDate = strtotime("+1 day", strtotime($date));
        $nextDate = date("Y-m-d", $nextDate);

        foreach ($timeList as $key => $val) {

            $start = explode("-", $val['time'])[0];
            $end = explode("-", $val['time'])[1];


            if ($val['prefx'] == '') {
                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);
            } else {
                $startTime = strtotime($nextDate . " " . $start);
                $endTime = strtotime($nextDate . " " . $end);
            }


            $timeList[$key]['selected'] = false;
            $timeList[$key]['isFree'] = true;
            $timeList[$key]['isUseing'] = false;


            foreach ($bookList as $k => $v) {
                if (($startTime >= $v['start_time'] && $endTime < $v['end_time']) || ($v['end_time'] > $startTime && $v['end_time'] <= $endTime) || ($v['start_time'] > $startTime && $v['start_time'] < $endTime)) {
                    $timeList[$key]['isFree'] = false;
                    if (time() >= $startTime && time() <= $endTime) {
                        $timeList[$key]['isUseing'] = true;
                    }
                }

            }
            $timeList[$key]['isClean'] = false;

            foreach ($cleanList as $k => $v) {
                if (($startTime >= $v['start_time'] && $endTime <= $v['end_time']) || ($v['end_time'] > $startTime && $v['end_time'] < $endTime)) {
                    if ($v['status'] != 'done') {
                        $timeList[$key]['isClean'] = true;
                    }
                }

            }


        }

        $this->success('', $timeList);
    }

    /**
     * 按小时获取
     */
    public function roomTimeTwo()
    {

        $ret = array();
        $room_id = $this->request->param('id');
        $date = $this->request->param('date');
        $hour = $this->request->param('hour');

        $today = date("Y-m-d");
        if ($today == $date) {
            //今天 ，从当前时间来计算
        } else {

        }


        $this->success('', $ret);
    }


    /**
     * 按套餐获取
     */
    public function roomTimeThree()
    {

        $ret = array();
        $room_id = $this->request->param('id');
        $date = $this->request->param('date');

        $roomSetModel = new Shoproomset();
        $list = $roomSetModel->where('room_id', $room_id)->select();
        $ret['list'] = $list;
        $this->success('', $ret);
    }

    /**
     * 余额可用门店
     */
    public function balanceShopList()
    {
        $id = $this->request->param('id');
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $id)->find();
        $shop['logo'] = cdnurl($shop['logo'], true);

        $covers = explode(",", $shop['cover']);
        $tag = explode(",", $shop['tag']);
        $cover = array();
        foreach ($covers as $key => $val) {
            $cover[] = cdnurl($val, true);
        }
        $shop['cover'] = $cover;
        $shop['tag'] = $tag;
        $list = array();
        $list[] = $shop;
        $this->success('', $list);
    }


    /**
     * 店铺wifi信息
     */
    public function getWifiInfo()
    {

        $shop_id = $this->request->param('shop_id');
        $shopWifiModel = new Shopwifi();
        $wifi = $shopWifiModel->where('shop_id', $shop_id)->find();
        if (!$wifi) {
            $this->error("店铺暂未设置wifi信息");
        } else {
            $this->success('', $wifi);
        }
    }


    public function getNotice()
    {

        $shop_id = $this->request->param('shop_id');
        $noticeModel = new Notice();
        $notice = $noticeModel->where('shop_id', $shop_id)->order('create_time', 'desc')->find();

        if ($notice) {
            $contents = explode(",", $notice['content']);
            $newList = array();

            if (count($contents) > 0) {
                foreach ($contents as $key => $val) {
                    $obj = array();
                    $obj['content'] = $val;
                    $newList[] = $obj;

                }
            }
            $notice['content'] = $newList;
        }

        $this->success('', $notice);
    }


    public function doShopFav()
    {

        $user = $this->auth->getUser();
        $shop_id = $this->request->param('shop_id');

        $shopFavModel = new Shopfav();
        $fav = $shopFavModel->where('shop_id', $shop_id)->where('user_id', $user['id'])->find();
        if ($fav) {
            $shopFavModel->where('id', $fav['id'])->delete();
            $isFav = -1;
        } else {
            $shopFavModel->insert(['user_id' => $user['id'], 'shop_id' => $shop_id]);
            $isFav = 1;
        }
        $this->success("", $isFav);
    }

    public function favShopList()
    {

        $user = $this->auth->getUser();
        $shopFavModel = new Shopfav();
        $list = $shopFavModel->with(['shop'])->where('Shopfav.user_id', $user['id'])->select();
        foreach ($list as $key => $val) {
            $list[$key]['shop']['logo'] = cdnurl($val['shop']['logo'], true);
        }
        $this->success('', $list);
    }

    public function roomInfo()
    {

        $id = $this->request->param('id');
        $shopRoomModel = new Shoproom();
        $shopModel = new \app\admin\model\Shop();
        $room = $shopRoomModel->where('id', $id)->find();
        $shop = $shopModel->where('id', $room['shop_id'])->find();
        $ret = array();
        $ret['room_name'] = $room['name'];
        $ret['shop_name'] = $shop['name'];
        $this->success('', $ret);
    }


    public function codeChargeInfo()
    {

        $code = $this->request->param('code');
        $chargeCodeModel = new Chargecode();
        $chargeCode = $chargeCodeModel->where('code', $code)->find();
        if (!$chargeCode) $this->error("兑换码不存在");
        if ($chargeCode['status'] == 'used') $this->error("兑换码已兑换");


        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $chargeCode['shop_id'])->find();

        $ret = array();
        $ret['shop_name'] = $shop['name'];
        $ret['amount'] = $chargeCode['price'];
        $this->success('', $ret);
    }

    public function doCodeCharge()
    {

        $code = $this->request->param('code');
        $chargeCodeModel = new Chargecode();
        $chargeCode = $chargeCodeModel->where('code', $code)->find();
        if (!$chargeCode) $this->error("兑换码不存在");
        if ($chargeCode['status'] == 'used') $this->error("兑换码已兑换");


        $balanceModel = new Userbalance();
        $balance = $balanceModel->where('charge_code', $code)->find();
        if ($balance) $this->error("此券不能兑换");
        $chargeCodeModel->where('id', $chargeCode['id'])->update(['status' => 'used']);

        $user = $this->auth->getUser();
        $balanceModel->insert(['user_id' => $user['id'], 'type' => 'in', 'amount' => $chargeCode['price'],
            'mark' => '充值卡兑换', 'create_time' => time(), 'shop_id' => $chargeCode['shop_id'], 'order_id' => -1, 'charge_code' => $code]);
        $this->success('兑换成功');
    }

    //查询0抽佣店铺每月10号应扣除的金额
    public function getShopMinMoney($shop_id)
    {
        $shopRoomModel = new Shoproom();
        //查询店铺包厢数量
        $shopRoom = $shopRoomModel->where('shop_id', $shop_id)->count();
        //查询台桌数量
        $shopTableModel = new \app\admin\model\Shoptable();
        $shopTable = $shopTableModel->where('shop_id', $shop_id)->count();
        $total = $shopRoom + $shopTable;

        //查询抽佣的相关参数
        $shopCommissionModel = new Commission();
        $shopCommInfo = $shopCommissionModel->where('shop_id',$shop_id)->find();
        if(empty($shopCommInfo)){
            if ($total <= 7) {//数量少于7台则扣除599，大于7台，每增加1台多扣除85元/月
                $totalMoney = 599;
            } else {
                $totalMoney = 599 + ($total - 7) * 85;
            }
        }else{
            if ($total <= 7) {
                $totalMoney = $shopCommInfo['min_amount'];
            } else {
                $totalMoney = $shopCommInfo['min_amount'] + ($total - 7) * $shopCommInfo['single_amount'];
            }
        }
        return $totalMoney;
    }

}
